package com.zhoukun.nacos.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zhoukun.cloud.CommentRest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhoukun 86547462@qq.com
 * @version 1.0
 * @date 2020/11/1 2:00
 */
@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    /*
    * blockHandler:服务请求会被降级为blockHandler方法sentinel定义的失败调用或限制调用，若本次访问被限流或服务降级，则调用blockHandler指定的接口。
    * fallback:失败调用，若本接口出现未知异常，则调用fallback指定的接口。
    * */
    @SentinelResource(value = "byResource",blockHandler = "blockbyResource",fallback = "fallbackResource")
    public CommentRest commentRest(
            @RequestParam(value = "num",required = false) Integer num)
    {
        if(num!=null&&num<0)
        {
            throw new RuntimeException("参数不能为负数！");
        }
        return  new CommentRest().setCode(200).setMessage("success").setData("服务请求成功！");
    }

    public CommentRest blockbyResource(Integer num,BlockException exception)
    {
        return  new CommentRest().setCode(403).setMessage("blockHandler实例："+exception.getClass().getCanonicalName()).setData("服务请求失败！");
    }
    public CommentRest fallbackResource(Integer num,Throwable e)
    {
        return  new CommentRest().setCode(403).setMessage("fallback实例："+e.getMessage()).setData("服务请求失败！");
    }

}
